<?php
/**
 * @name ErrorController
 * @desc 错误控制器, 在发生未捕获的异常时刻被调用
 * @see http://www.php.net/manual/en/yaf-dispatcher.catchexception.php
 * @author luomo-l540\luomo
 */

use Doraemon\pockets\constInterface\ApiCode;
use Doraemon\tools\Log;
use Doraemon\pockets\action\ApiAction;

class ErrorController extends Yaf_Controller_Abstract {

	//从2.1开始, errorAction支持直接通过参数获取异常
	public function errorAction($exception) {
		//1. assign to view engine
//        var_dump($exception->getMessage(), $exception->getFile());exit;
//		$this->getView()->assign("exception", $exception);
		//5. render by Yaf
        $this->setError($exception);
    }

    protected function setError($e = null)
    {
        $reportCode = uniqid();
        $traceId = $_SERVER['HTTP_TRACEID'] ? : $_SERVER['HTTP_X_REQUEST_ID'];
        $view = [
            "code" => ApiCode::API_CODE_EXCEPTION,
            "msg" => ApiAction::API_CODE_EXCEPTION_TEXT . "反馈码：" . $reportCode,
            "feedback_code" => ApiAction::EXCEPTION_TYPE_BUSINESS . '#' . $traceId . '#' . $reportCode,
        ];

        $logMethod = 'api_error-' . $view['code'] . '_error';
        Log::$logMethod(implode(Log::DEFAULE_LOG_SEPARATOR,
            [
                $e ? $e->getLine() : "",
                $reportCode,
            ]), [
            $e ?: "",
            $this->getRequest(),
            $this->getRequest()->getQuery(),
            $this->getRequest()->getPost()
        ]);
        $this->getResponse()->setBody(json_encode($view, JSON_UNESCAPED_UNICODE));
    }
}
